package component.fy.com.common_module.services;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;

import java.util.Timer;
import java.util.TimerTask;

import component.fy.com.common_module.R;
import component.fy.com.common_module.baidu.LocationService;
import component.fy.com.common_module.constant.AppConstant;
import component.fy.com.common_module.base.BaseCommonApp;
import component.fy.com.common_module.bean.PostBackLocationBean;
import component.fy.com.common_module.retrofit.RetrofitManager;
import component.fy.com.common_module.utils.JsonUtil;
import component.fy.com.common_module.utils.LogUtil;
import component.fy.com.common_module.utils.SharedPreDataBase;

/**
 * 后台发送定位数据的服务
 */
public class KeepLiveService extends Service {
    private static final String TAG = "KeepLiveService";

    public static final int NOTIFICATION_ID = 0x11;

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private boolean isStop = false;
    private static int delay = 1000; // 1s
    private static int period = 1000; // 1s
    private LocationService locationService;
    private double latitude = 0.0;//纬度
    private double longitude = 0.0;//经度

    public KeepLiveService() {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 触发定时器
        if (!isStop) {
            //Log.i("K", "开始服务");
            startTimer();
        }
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        locationService = BaseCommonApp.getBaseApp().getLocationService();
        locationService.registerListener(locationListener);
        //配置定位参数
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();

        //API 18以下，直接发送Notification并将其置为前台
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            startForeground(NOTIFICATION_ID, new Notification());
        } else {
            //API 18以上，发送Notification并将其置为前台后，启动InnerService
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            startForeground(NOTIFICATION_ID, builder.build());
            startService(new Intent(this, InnerService.class));
        }
    }

    /*
     * 定时器 每60分钟执行一次
     */
    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        //Log.i(TAG, "count: " + String.valueOf(count++));
        isStop = true;
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //Log.i(TAG, "count: " + String.valueOf(count++));
                    do {
                        try {
                            locationService.start();
                            if (locationService != null && locationService.isStart()) {
                                locationService.start();
                            } else {
                                //Log.d("LocSDK3","locClient is null or not started");
                                Thread.sleep(1000 * 60 * 5);//暂停5分钟
                            }
                        } catch (InterruptedException e) {
                        }
                    } while (isStop);
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, delay, period);
        }
    }

    /**
     * 停止计时
     */
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        isStop = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 停止定时器
        if (isStop) {
            LogUtil.i(TAG, "服务停止");
            stopTimer();
        }
    }

    /**
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDAbstractLocationListener locationListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (null != bdLocation && bdLocation.getLocType() != BDLocation.TypeServerError) {
                LogUtil.e(TAG, "经度 = " + bdLocation.getLongitude() + "\n纬度 = " + bdLocation.getLatitude());
                if (!TextUtils.equals("null", bdLocation.getAddrStr().toString())) {
                    LogUtil.e(TAG, "不等于null");
                    locationService.stop();
                    latitude = bdLocation.getLatitude();
                    longitude = bdLocation.getLongitude();
                    postLocation();
                }
            }
        }
    };

    /**
     * 发送定位数据
     */
    private void postLocation() {
//        ToastUtil.showToast("发送定位");
        String factoryId = SharedPreDataBase.getStringData(AppConstant.User_Info_Driver_FactoryId);
        String carInfoId = SharedPreDataBase.getStringData(AppConstant.User_Info_Driver_CarInfoId);
        int employeeDriverid = SharedPreDataBase.getIntData(AppConstant.User_userId);
        String token = SharedPreDataBase.getStringData(AppConstant.User_accessToken);

        if (TextUtils.isEmpty(factoryId) || TextUtils.isEmpty(carInfoId)) {
            if (locationService != null) {
                locationService.unregisterListener(locationListener); //注销掉监听
                locationService.stop();//停止定位服务
                // 停止定时器
                stopTimer();
            }
            stopSelf();
            return;
        }

        PostBackLocationBean locationBean = new PostBackLocationBean();
        locationBean.setCarInfoId(carInfoId);
        locationBean.setEmployeeDriverid(employeeDriverid);
        locationBean.setFactoryId(factoryId);
        locationBean.setLatitude(latitude + "");
        locationBean.setLongitude(longitude + "");
        String jsonStr = JsonUtil.toJson(locationBean);

        RetrofitManager.doPost("Bearer " + token, "api/services/app/CarMap/Create", jsonStr);
    }

    public static class InnerService extends Service {
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();
            //发送与KeepLiveService中ID相同的Notification，然后将其取消并取消自己的前台显示
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            startForeground(NOTIFICATION_ID, builder.build());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    stopForeground(true);
                    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    manager.cancel(NOTIFICATION_ID);
                    stopSelf();
                }
            }, 100);
        }
    }
}
